package com.irrigation.controller;

import com.irrigation.dto.SensorDataDto;
import com.irrigation.service.SensorDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/sensor-data")
@RequiredArgsConstructor
public class SensorDataController {

    private final SensorDataService sensorDataService;

    @GetMapping
    public ResponseEntity<List<SensorDataDto>> getAllSensorData() {
        return ResponseEntity.ok(sensorDataService.getAllSensorData());
    }

    @GetMapping("/{id}")
    public ResponseEntity<SensorDataDto> getSensorDataById(@PathVariable Long id) {
        return ResponseEntity.ok(sensorDataService.getSensorDataById(id));
    }

    @GetMapping("/sensor/{sensorId}")
    public ResponseEntity<List<SensorDataDto>> getSensorDataBySensorId(@PathVariable Long sensorId) {
        return ResponseEntity.ok(sensorDataService.getSensorDataBySensorId(sensorId));
    }

    @GetMapping("/sensor/{sensorId}/range")
    public ResponseEntity<List<SensorDataDto>> getSensorDataByTimeRange(
            @PathVariable Long sensorId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {
        return ResponseEntity.ok(sensorDataService.getSensorDataByTimeRange(sensorId, startTime, endTime));
    }

    @GetMapping("/sensor/{sensorId}/latest")
    public ResponseEntity<List<SensorDataDto>> getLatestSensorData(
            @PathVariable Long sensorId,
            @RequestParam(defaultValue = "10") int limit) {
        return ResponseEntity.ok(sensorDataService.getLatestSensorData(sensorId, limit));
    }

    @PostMapping
    public ResponseEntity<SensorDataDto> createSensorData(@RequestBody SensorDataDto sensorDataDto) {
        return ResponseEntity.ok(sensorDataService.createSensorData(sensorDataDto));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteSensorData(@PathVariable Long id) {
        sensorDataService.deleteSensorData(id);
        return ResponseEntity.noContent().build();
    }
}
